#!/bin/bash
# This script creates a kubeflow deployment on minikube
# It checks for kubectl, ks
# Creates the ksonnet app, installs packages, components and then applies them

set -xe

PWD_DIR="/usr/local"
KUBEFLOW_NAMESPACE=${KUBEFLOW_NAMESPACE:-"kubeflow"}
KUBEFLOW_REPO=${KUBEFLOW_REPO:-"${PWD_DIR}/kubeflow_repo"}
KUBEFLOW_VERSION=${KUBEFLOW_VERSION:-"0.2.2"}
KUBEFLOW_DEPLOY=${KUBEFLOW_DEPLOY:-true}

if [[ ! -d "${KUBEFLOW_REPO}" ]]; then
  if [ "${KUBEFLOW_VERSION}" == "master" ]; then
    TAG=${KUBEFLOW_VERSION}
  else
    TAG=v${KUBEFLOW_VERSION}
  fi
  TMPDIR=$(mktemp -d /tmp/tmp.kubeflow-repo-XXXX)
  curl -L -o ${TMPDIR}/kubeflow.tar.gz https://gitee.com/wisteriasomnus/kubeflow/attach_files/download?i=160402&u=http%3A%2F%2Ffiles.git.oschina.net%2Fgroup1%2FM00%2F04%2F9F%2FPaAvDFt079GAFS53AFK-sqltr2o1463.gz%3Ftoken%3D27fde38b8109eb9fad790b25c422c10c%26ts%3D1534390253%26attname%3Dkubeflow-0.2.2.tar.gz
  tar -xzvf ${TMPDIR}/kubeflow.tar.gz  -C ${TMPDIR}
  # GitHub seems to strip out the v in the file name.
  SOURCE_DIR=$(find ${TMPDIR} -maxdepth 1 -type d -name "kubeflow*")
  mv ${SOURCE_DIR} "${KUBEFLOW_REPO}"
fi

source "${KUBEFLOW_REPO}/scripts/util.sh"

check_install ks
check_install kubectl

# Name of the deployment
DEPLOYMENT_NAME=${DEPLOYMENT_NAME:-"kubeflow"}

KUBEFLOW_KS_DIR=${KUBEFLOW_KS_DIR:-"${PWD_DIR}/${DEPLOYMENT_NAME}_ks_app"}

cd $(dirname "${KUBEFLOW_KS_DIR}")
ks init $(basename "${KUBEFLOW_KS_DIR}")
cd "${KUBEFLOW_KS_DIR}"

kubectl config set-context $(kubectl config current-context) --namespace=${KUBEFLOW_NAMESPACE}
# Add the local registry
ks registry add kubeflow "${KUBEFLOW_REPO}/kubeflow"

# Install packages
ks pkg install kubeflow/argo
ks pkg install kubeflow/core
ks pkg install kubeflow/examples
ks pkg install kubeflow/katib
ks pkg install kubeflow/mpi-job
ks pkg install kubeflow/pytorch-job
ks pkg install kubeflow/seldon
ks pkg install kubeflow/tf-serving

# Generate all required components
ks generate kubeflow-core kubeflow-core

# Enable collection of anonymous usage metrics
# Skip this step if you don't want to enable collection.
ks param set kubeflow-core reportUsage false
ks param set kubeflow-core tfJobUiServiceType NodePort
ks param set kubeflow-core jupyterHubServiceType NodePort
ks param set kubeflow-core AmbassadorServiceType NodePort

# Apply the components generated
if ${KUBEFLOW_DEPLOY}; then
  ks apply default
fi

exit 0